package ecommerce.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

import org.apache.commons.dbcp.BasicDataSource;

public class DataSource {

	private BasicDataSource bds;
	private static DataSource dataSource = new DataSource();
	
	private DataSource() {
		bds = new BasicDataSource();
		bds.setDriverClassName("com.mysql.jdbc.Driver");
		bds.setUrl("jdbc:mysql://localhost:3306/comp5347_assignment2");
		bds.setUsername("root");
		bds.setPassword("basser");
		bds.setMaxActive(5);
	}
	
	public static DataSource getInstance() {
		return dataSource;
	}
	
	public Connection getConnection() throws SQLException {
		return bds.getConnection();
	}
	
	public void createDatabase() {
		PreparedStatement ps = null;
		Scanner read = null;
		
		try {
			Connection connection = bds.getConnection();
			read = new Scanner(this.getClass().getResourceAsStream("database_script.txt"));
			while(read.hasNextLine()) {
				ps = connection.prepareStatement(read.nextLine());
				ps.execute();
			}
			ps.close();
			read.close();
		}catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try { 
				if(ps != null) { ps.close(); }
				if(read != null) { read.close(); }
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
}
